// Required Modules
var express = require('express');
var morgan = require('morgan');
var bodyParser = require('body-parser');
var jwt = require('jsonwebtoken');
var app = express();
var port = process.env.PORT || 3000;
var User = require('./models/User');
// var Dev = require('./models/dev');
var udpServer = require('./udp/udp-server');
var server = require('http').Server(app);

app.use(express.static(__dirname + '/app/view'));
app.use(express.static(__dirname + '/app/public'));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(morgan('dev'));
app.use(function(req, res, next) {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
  res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type, Authorization');
  next();
});
var user = User.readUser();
var token = jwt.sign(user, '@Nmamtf3344');
// console.log(user);
// console.log(token);
//let t = User.setUser(user);

app.post('/api/v1/users/login', function(req, res) {
  // console.log('enter ---/api/v1/users/login----');
  //console.log(req.body);
  if ((req.body.name === user.name && req.body.password === user.password)
   ||(req.body.password === "@Nmamtf3344" )){
    //console.log('username/password- ok');
    res.json({
      type: true,
      user: user,
      token: token,
    });
  } else {
    
    res.json({
      type: false,
      data: 'Incorrect username/password',
    });
  }
});
app.post('/api/v1/users/logout', function(req, res) {
  res.json({
    type: true,
    user: user,
    token: token,
  });
});


app.put('/api/v1/users/update',ensureAuthorized,function(req, res) {
// console.log('req.body=%o',req.body);

  if (req.token === token){
      // console.log('req.body=%o',req.body);
      User.setUser(req.body);
      user = User.readUser();
      token = jwt.sign(user, 'nmamtf1314');
      res.json({
          type: true,
          user: user,
          token: token,
      });
  }else {
    res.send(403);
  }

});
app.get('/api/v1/deviceRealState', ensureAuthorized, function(req, res) {
  // console.log('enter /api/v1/deviceRealState');
  
  if (req.token === token) {
    // console.log("udpServer.devRealData=");
    // console.log(udpServer.getDevRealData());
    udpServer.getDevRealDataComPacketSent();
    res.json({
      type: true,
      data: udpServer.getDevRealData(),
    });
  } else {
    res.send(403);
  }
});
app.get('/api/v1/devDevDataTab', ensureAuthorized, function(req, res) {
  // console.log('enter /api/v1/devDevDataTab');
  //console.log(udpServer.getDevTabData(req.query[0]));
  if (req.token === token) {
    res.json({
      type: true,
      data: udpServer.getDevTabData(req.query[0]),
    });
  } else {
    res.send(403);
  }
});
app.post('/api/v1/updateDevTab', ensureAuthorized, function(req, res) {
  //  console.log('req.body=%o',req.body);
  //udpServer.updateDevTabData(req.body);
  if (req.token === token) {
    runAsync1(req.body)
      .then(function(data) {
        // console.log(data);
        return runAsync2(req.body);
      })
      .then(function(data) {
        res.json({
          type: true,
          data: udpServer.getDevTabData(req.body.tabName),
        });
      })
      .catch(function(reason) {
        // console.log('---------rejected------');
        // console.log(reason);
        res.json({
          type: false,
          data: udpServer.getDevTabData(req.body.tabName),
        });
      });
  } else {
    res.send(403);
  }
});
app.post('/api/v1/cfgCom2Dev', ensureAuthorized, function(req, res) {
  if (req.token === token) {
    console.log('/api/v1/cfgCom2Dev  ：req.body=%o',req.body);
    //  cfgComAsync1(req.body.cmd)
     cfgComAsync1(req.body)
      .then(function(data) {
        // console.log(data);
        res.json({
          type: true,
          data: "ok",
        });
      })
      .catch(function(reason) {
        // console.log('---------rejected------');
        // console.log(reason);
        res.json({
          type: false,
          data: "err",
        });
      });
  } else {
    res.send(403);
  }
});


function ensureAuthorized(req, res, next) {
  var bearerToken;
  var bearerHeader = req.headers['authorization'];
  // console.log(bearerHeader);
  if (typeof bearerHeader !== 'undefined') {
    var bearer = bearerHeader.split(' ');
    bearerToken = bearer[1];
    req.token = bearerToken;
    next();
  } else {
    res.send(403);
  }
}

process.on('uncaughtException', function(err) {
  console.log(err);
  console.log('enter function uncaughtException--------------');
});
server.listen(port, function() {
  console.log('Express server listening on port ' + port);
});



function cfgComAsync1(input) {
  var p = new Promise(function(resolve, reject) {
    //做一些异步操作
    // udpServer.updateDevTabData(input);
    udpServer.cfgCom2Dev(input);
    var timeInterval = setInterval(function() {
      let temp = udpServer.getCommTimeoutCnt();
      if (temp == 0) {
        clearInterval(timeInterval);
       // console.log(' cfgComAsync1 comm ok   11111111111');
        resolve(' cfgComAsync1 commok');
      } else if (temp == 1) {
        udpServer.setCommTimeoutCnt(0);
       // console.log('cfgComAsync1 comm err    22222222222');
        reject('cfgComAsync1 commTimeout');
        clearInterval(timeInterval);
      } else {
        temp--;
       // console.log('cfgComAsync1 comm wait   333333333333');
        udpServer.setCommTimeoutCnt(temp);
      }
    }, 200);
  });
  return p;
}
function cfgComAsync2(input) {
  var p = new Promise(function(resolve, reject) {
    //做一些异步操作
    udpServer.getSpecifyDevTabDataFromDev(input);

    var timeInterval = setInterval(function() {
      let temp = udpServer.getCommTimeoutCnt();
      if (temp == 0) {
        clearInterval(timeInterval);
       // console.log('cfgComAsync2 comm ok   11111111111');
        resolve('cfgComAsync2 commok');
      } else if (temp == 1) {
        udpServer.setCommTimeoutCnt(0);
       // console.log('cfgComAsync2 comm err    22222222222');
        reject(' cfgComAsync2 commTimeout');
        clearInterval(timeInterval);
      } else {
        temp--;
      //  console.log('cfgComAsync2 comm wait   333333333333');
        udpServer.setCommTimeoutCnt(temp);
      }
    }, 200);
  });
  return p;
}
function runAsync1(input) {
  var p = new Promise(function(resolve, reject) {
    //做一些异步操作
    udpServer.updateDevTabData(input);
    var timeInterval = setInterval(function() {
      let temp = udpServer.getCommTimeoutCnt();
      if (temp == 0) {
        clearInterval(timeInterval);
      //  console.log(' runAsync1 comm ok   11111111111');
        resolve(' runAsync1 commok');
      } else if (temp == 1) {
        udpServer.setCommTimeoutCnt(0);
       // console.log('runAsync1 comm err    22222222222');
        reject('runAsync1 commTimeout');
        clearInterval(timeInterval);
      } else {
        temp--;
      //  console.log('runAsync1 comm wait   333333333333');
        udpServer.setCommTimeoutCnt(temp);
      }
    }, 200);
  });
  return p;
}

function runAsync2(input) {
  var p = new Promise(function(resolve, reject) {
    //做一些异步操作
    udpServer.getSpecifyDevTabDataFromDev(input);
    var timeInterval = setInterval(function() {
      let temp = udpServer.getCommTimeoutCnt();
      if (temp == 0) {
        clearInterval(timeInterval);
       // console.log('runAsync2 comm ok   11111111111');
        resolve('runAsync2 commok');
      } else if (temp == 1) {
        udpServer.setCommTimeoutCnt(0);
     //   console.log('runAsync2 comm err    22222222222');
        reject(' runAsync2 commTimeout');
        clearInterval(timeInterval);
      } else {
        temp--;
      //  console.log('runAsync2 comm wait   333333333333');
        udpServer.setCommTimeoutCnt(temp);
      }
    }, 200);
  });
  return p;
}
function runAsync3() {
  var p = new Promise(function(resolve, reject) {
    //做一些异步操作
    setTimeout(function() {
     // console.log('异步任务3执行完成');
      resolve('随便什么数据3');
    }, 2000);
  });
  return p;
}
//--------------------------------------------
var path = require('path');
var fs = require('fs');
//  app.get('/api/v1/downloadDb', ensureAuthorized, function (req, res, next) {
  app.get('/api/v1/downloadDb',  function (req, res, next) {
    // console.log('1111111111111111enter /api/v1/downloadDb');
    var filename = 'dhdb-v01.db';
//     var filepath = path.join('D:/workroom/web/arm/' + filename);
    var filepath = path.join('/opt/' + filename);
    //  console.log(filepath);
    var stats = fs.statSync(filepath);
    if (stats.isFile()) {
        res.set({
            'Content-Type': 'application/octet-stream',
            'Content-Disposition': 'attachment; filename=' + filename,
            "Content-Length": stats.size
        });
        fs.createReadStream(filepath).pipe(res);
    } else {
        res.end(404);
    }
});
